﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using static System.Net.Mime.MediaTypeNames;
using System.Net;

namespace AuSys.Services.App.ActionFilters
{
    public class MasterKeyRequiredFilter(
        IConfiguration config)
        : IAsyncActionFilter
    {
        public const string masterKeyConfigKey = "MasterKey";
        public async Task OnActionExecutionAsync(
            ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string? key = config[masterKeyConfigKey];
            if (key is null) {
                context.Result = new ContentResult()
                {
                    Content = "配置项MasterKey未填",
                    ContentType = Text.Plain,
                    StatusCode = (int)HttpStatusCode.InternalServerError
                };
            }
            var keyInParam = context.ActionArguments
                .Where(x => x.Key.Equals("masterkey", StringComparison.InvariantCultureIgnoreCase))
                .Select(x => x.Value)
                .FirstOrDefault();
            string keyProvided = string.Empty;
            if (keyInParam is string keyStr)
                keyProvided = keyStr;
            if (keyProvided != key)
            {
                string msg = string.IsNullOrWhiteSpace(keyProvided)
                    ? "未提供MasterKey"
                    : "MasterKey不正确";
                context.Result = new ContentResult()
                {
                    Content = msg,
                    ContentType = Text.Plain,
                    StatusCode = (int)HttpStatusCode.Forbidden
                };
            }
            else
                await next();
        }
    }

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class MasterKeyRequiredAttribute
        : TypeFilterAttribute<MasterKeyRequiredFilter>
    {

    }
}
